package com.yeqian.utils;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Author:yeqian
 * @Date: 2020/12/2 19:23
 * 邮件工具类
 */
@Component
public class MailUtils {

    private JavaMailSenderImpl mailSender;

    public MailUtils(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * 发送简单邮件
     *
     * @param text  邮件正文
     * @param title 标题
     * @param to    接收方
     */
    public boolean sendSimpleMail(String text, String title, String... to) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject(title);//设置邮件标题
            message.setText(text);//设置邮件内容
            message.setTo(to);//设置发送给谁
            message.setFrom("798737426@qq.com");//设置从哪里来的
            //System.out.println("邮件内容"+message);
            System.out.println(mailSender.getUsername());
            mailSender.send(message);//发送邮件
            //发送成功返回true
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发送失败返回false
        return false;
    }

    /**
     * 发送复杂邮件
     *
     * @param text     邮件正文
     * @param title    标题
     * @param fileName 附件名
     * @param file     附件
     * @param to       接收方
     */
    public boolean sendComplexMail(String text, String title, String fileName, File file, String... to) {
        try {
            //一个复杂的邮件任务
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //组装邮件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject(title);
            helper.setText(text, true);
            helper.addAttachment(fileName, file);//添加附件
            helper.setTo(to);//设置发送给谁
            helper.setFrom("798737426@qq.com");//设置从哪里来的
            mailSender.send(mimeMessage);//发送邮件
            //发送成功返回true
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发送失败返回false
        return false;
    }
}
